package controllers

import (
	"cmt1-admin/models"
	"cmt1-admin/utils"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx"
)

func ExportExcel(c *gin.Context) {
	contentType := c.Request.Header.Get("Content-Type")
	fmt.Println(contentType)

	feilds := c.PostFormMap("feilds")
	page := c.PostForm("page")
	limit := c.PostForm("limit")

	pageT, _ := strconv.Atoi(page)
	limitT, _ := strconv.Atoi(limit)

	file := xlsx.NewFile()
	sheet, err := file.AddSheet("Sheet1")
	if err != nil {
		handleErr(c, 404, "添加sheet失败...")
		return
	}

	// feilds是map，无序，保证有序，放入数组中
	feildLst := make([]string, 0)
	length := len(feilds)
	for i := 0; i < length; i++ {
		feildLst = append(feildLst, feilds[strconv.Itoa(i)])
	}

	row := sheet.AddRow()
	var cell *xlsx.Cell
	// 表插入表头
	for _, title := range feildLst {
		cell = row.AddCell()
		cell.Value = title
	}

	lst := make([]*models.GameUser, 0)
	// lst := make([]interface{}, 0)
	err = GameDB.FindPage("user", pageT, limitT, nil, nil, &lst)
	// err = GameLogDB.FindPage("WaBaoLog", 1, 1000, nil, nil, &lst)
	if err != nil {
		handleErr(c, 404, "获取数据失败...")
		return
	}
	// 遍历所有元素
	for _, item := range lst {
		row = sheet.AddRow()
		typeOf := reflect.TypeOf(item)   // 字段
		valueOf := reflect.ValueOf(item) // 值
		// 是指针，获取他指针指向的元素
		if valueOf.Kind() == reflect.Ptr {
			typeOf = typeOf.Elem()
			valueOf = valueOf.Elem()
		}
		// 获取需要的字段
		for _, field := range feildLst {
			fieldName, _ := typeOf.FieldByName(field)
			fieldValue := valueOf.FieldByName(field)

			cell = row.AddCell()
			// 字段包含时间
			if strings.Contains(fieldName.Name, "Time") {
				mytime := utils.UnixToTime(fieldValue.Int(), 0)
				timeStr := utils.TimeToLayout(mytime)
				cell.SetValue(timeStr)
			} else {
				cell.SetValue(fieldValue)
			}
		}
	}

	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename=1.xlsx")
	c.Header("Content-Transfer-Encoding", "binary")
	err = file.Write(c.Writer)
	if err != nil {
		handleErr(c, 404, "写入数据失败...")
		return
	}
	return
}

var tags = [][]string{
	{"1", "小昆虫1"},
	{"2", "小昆虫2"},
}

func ExportExcelUser(c *gin.Context) (filename string, err error) {
	file := xlsx.NewFile()
	sheet, err := file.AddSheet("标签信息")
	if err != nil {
		return
	}
	titles := []string{"ID", "名字"}
	row := sheet.AddRow()
	var cell *xlsx.Cell
	for _, title := range titles {
		cell = row.AddCell()
		cell.Value = title
	}
	for _, item := range tags {
		row = sheet.AddRow()
		for _, itemT := range item {
			cell = row.AddCell()
			cell.Value = itemT
		}
	}
	timestr := strconv.FormatInt(time.Now().Unix(), 10)
	filename = "user-" + timestr + ".xlsx"

	err = file.Save(filename)
	if err != nil {
		return
	}
	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.Header("Content-Transfer-Encoding", "binary")
	err = file.Write(c.Writer)
	if err != nil {
		return
	}
	return
}
